package edu.unc.comp410.colemangeer.data;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;

import com.mysql.jdbc.CommunicationsException;

import edu.unc.comp410.sharedcode.SQLutilities;
import edu.unc.comp410.sharedcode.ValidateUtilities;


public class ConstraintGateway implements IConstraintGateway {
	
		// Constants
	
		// Data members
	private static Connection conn;
	private static Statement stmt;
	private static String DB;	// Useful for debugging.
	private static String MACH;	// Useful for debugging.
	private static Logger log = Logger.getLogger( ConstraintGateway.class );
	
	/**
	 * Default constructor.
	 */
	public ConstraintGateway( String db, String mach ) 
	throws ClassNotFoundException, CommunicationsException {
		ValidateUtilities.checkForContent( db );
		ValidateUtilities.checkForContent( mach );
		DB = db;
		MACH = mach;
		conn = SQLutilities.getConnection( db, mach );
		stmt = SQLutilities.getStatement( conn );
	}
	
	/**
	 * Search the DB table IntegerConstraint for a
	 *    constraint named constraintName
	 * @param constraintName = name of constraint to search for
	 * @return result of searching for constraintName
	 */
	public IntegerConstraintGatewayResult
	findIntegerConstraint(  String constraintName  ) {
		ValidateUtilities.checkForContent( constraintName );
		IntegerConstraintGatewayResult result = 
			new IntegerConstraintGatewayResult();
		String query = "SELECT ConstraintName, Min, Max"
			+ " FROM IntegerConstraint WHERE ConstraintName = '" 
			+ constraintName +"'";
		log.debug( "query = " + query );

		try {
			ResultSet rs = stmt.executeQuery( query );
			if( rs.next() ) {
				result.success = true;
				result.Min = rs.getInt( "Min" );
				result.Max = rs.getInt( "Max" );
			}
		} catch (SQLException e) {
			System.err.println( e );
			e.printStackTrace();
		}
		return result;
	}
	
	public static String getDB() { return DB; }
	public static String getMACH() { return MACH; }
	
	/**
	 * We were successful in obtaining both a DB
	 * connection and a DB statement?
	 */
	public boolean successfulDBconnection() {
		return( null != conn && null != stmt );
	}
	
	
	@Override public String toString() {
		String result = "ConstraintGateway: db = " + DB
			+ " machine = " + MACH;
		return result;
	}
	
}
